/*
 * Copyright [2009] [Marcin Rzeźnicki]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
 */
package mr.go.yaxc.actions;

import mr.go.yaxc.Action;
import mr.go.yaxc.ConfigurationError;
import mr.go.yaxc.ScopeHandler;

import org.xml.sax.Attributes;

/**
 * This action references object <i>id</i> from the global context
 * 
 * <h6>on xml element start:</h6> Obtains reference to an object from the global
 * context and sets it as <i>object</i> in current scope <h6>on xml element end:
 * </h6> passes <i>object</i> to parent's <i>params</i> <h6>prerequisites:</h6>
 * existing reference <i>id</i> in the global context, otherwise warning is
 * emitted and null passed <h6>attributes:</h6>
 * <table>
 * <tr>
 * <th>Attribute name</th>
 * <th>What is it for?</th>
 * <th>Required?</th>
 * </tr>
 * <tr>
 * <td><i>id</i></td>
 * <td>used to reference object from the global context</td>
 * <td>yes</td>
 * </tr>
 * </table>
 *<p>
 * Example:<br>
 * 
 * <pre>
 * &lt;Ref id=&quot;externalSomethingHolder&quot;&gt;
 * 		&lt;Call name=&quot;setSomethings&quot;&gt;
 * 			&lt;Ref id=&quot;somethings&quot; /&gt;
 * 		&lt;/Call&gt;
 * 	&lt;/Ref&gt;
 * </pre>
 * 
 * </p>
 * 
 * 
 * @author Marcin Rzeźnicki
 * 
 */
public class Ref extends Action {

    @Override
    public void carryOut(String name, Attributes attributes,
                         ScopeHandler handler)
            throws Exception {
        String id = attributes.getValue(getAttribute("id"));
        if (id == null) {
            throw new ConfigurationError("Missing attribute: " + getAttribute(
                    "id"));
        }
        final Object ref = handler.getReference(id);
        if (ref == null) {
            return;
        }
        if (handler.getLogger().isDebugEnabled()) {
            handler.getLogger().debug("Ref: {}",
                                      ref.toString());
        }
        object = ref;
    }

    @Override
    public void processed(String body, ScopeHandler handler)
            throws Exception {
        handler.tryAddParam(object);
    }
}
